﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using UnityEngine.UI;
public class LogDialog : MonoBehaviour
{

    public static LogDialog instance;

    private List<string> list = new List<string>();
    private int count = 0;
    private bool isOpen;
    private int _offset = 0;
    private Transform itemGrid;
    private Transform scrollbar;
    private Image bgImg;

    /// <summary>
    /// 拷贝回调
    /// 暴露出去，方便添加拷贝方法
    /// </summary>
    public Action<string> CopyAction = null;

    private int MaxNum = 200;   //显示数量
    public static readonly Dictionary<LogType, Color> logTypeColors = new Dictionary<LogType, Color>
        {
            { LogType.Assert, Color.green },
            { LogType.Error, Color.red },
            { LogType.Exception, Color.red },
            { LogType.Log, Color.white },
            { LogType.Warning, Color.yellow },
        };


    private void Awake()
    {
        instance = this;
        isOpen = true;
        itemGrid = transform.FindChild("ItemGrid");
        scrollbar = transform.FindChild("Scrollbar");
        bgImg = transform.GetComponent<Image>();
        //itemGrid.gameObject.SetActive(false);
        //scrollbar.gameObject.SetActive(false);
        //bgImg.enabled = false;
        Application.logMessageReceived += HandleLog;
    }

    // Use this for initialization
    void Start()
    {

        for (int i = 0; i < itemGrid.childCount; i++)
        {
            EventTriggerListener.Get(itemGrid.GetChild(i).gameObject).onClick = go =>
            {
                string log = go.GetComponent<Text>().text;
                if (CopyAction != null)
                {
                    CopyAction(log);
                }
                else
                {
                    TextEditor te = new TextEditor();
                    te.text = log;
                    te.OnFocus();
                    te.Copy();
                }
                Loger.Warring("LogDialog", "拷贝成功！");
            };
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (isOpen)
        {
            if (Loger.logs.Count > 0)
            {
                _ShowScreenLog(Loger.logs);
            }
        }
    }


//    void OnGUI()
//    {
//#if UNITY_EDITOR
//        GUI.color = Color.red;
//        if (GUI.Button(new Rect(Screen.width - 270, 2, 60, 28), "Log开关"))
//        {
//            isOpen = !isOpen;
//            itemGrid.gameObject.SetActive(isOpen);
//            scrollbar.gameObject.SetActive(isOpen);
//            bgImg.enabled = isOpen;
//        }
//#elif UNITY_TEST
//       GUI.color = Color.red;
//        if (GUI.Button(new Rect(Screen.width - 270, 2, 100, 50), "Log开关"))
//        {
//            isOpen = !isOpen;
//            itemGrid.gameObject.SetActive(isOpen);
//            scrollbar.gameObject.SetActive(isOpen);
//            bgImg.enabled = isOpen;
//        }
//#endif
//        GUI.color = Color.red;
//        if (GUI.Button(new Rect(Screen.width - 270, 2, 60, 28), "Log开关"))
//        {
//            isOpen = !isOpen;
//            itemGrid.gameObject.SetActive(isOpen);
//            scrollbar.gameObject.SetActive(isOpen);
//            bgImg.enabled = isOpen;
//        }

//    }


    /// <summary>
    /// 显示屏幕Log
    /// </summary>
    /// <param name="contentlist"></param>
    /// <param name="colorlist"></param>
    private void _ShowScreenLog(List<Log> contentlist)
    {
        //Transform itemGrid = _Log.transform.FindChild("ItemGrid");

        if (Loger.logs.Count <= 15)
        {
            // _Log.transform.FindChild("Scrollbar").gameObject.SetActive(false);
            scrollbar.gameObject.SetActive(false);
            for (int i = 0; i < itemGrid.childCount; i++)
            {
                if (i >= contentlist.Count) continue;

                itemGrid.GetChild(i).GetComponent<Text>().text = contentlist[i].message + "\n" + contentlist[i].tag;
                itemGrid.GetChild(i).GetComponent<Text>().color = logTypeColors[contentlist[i].type];
            }
        }
        else
        {
            scrollbar.gameObject.SetActive(true);
            scrollbar.GetComponent<Scrollbar>().size = (float)(15.0 / contentlist.Count);
            for (int i = 0; i < itemGrid.childCount; i++)
            {
                int index = i + contentlist.Count - 15 - _offset + 1;
                if (index > 0 && index < contentlist.Count)
                {
                    itemGrid.GetChild(i).GetComponent<Text>().text = contentlist[index].message + "\n" + contentlist[index].tag;
                    itemGrid.GetChild(i).GetComponent<Text>().color = logTypeColors[contentlist[index].type];
                }
                else
                {
                    //Debug.Log("index: " + index);
                }
            }


            float odd = (contentlist.Count - 15) / 100f;
            _offset = (int)(scrollbar.GetComponent<Scrollbar>().value * 100 * odd);
            //Debug.Log("_offset: " + _offset);
            //Debug.Log(_Log.transform.FindChild("Scrollbar").GetComponent<Scrollbar>().value);
            //Loger.Info("_offset: " + _offset);
        }
    }


    void HandleLog(string message, string tag, LogType type)
    {
        if (Loger.logs.Count > MaxNum)
            Loger.logs.RemoveAt(0);
        Loger.logs.Add(new Log
        {
            message = message,
            tag = tag,
            type = type,
        });
        //写入log文件
        //string str = DateTime.Now.ToString("HH:mm:ss") + message + "\n" + tag;
        //Loger.WriteLogForFile(str);
        if (type == LogType.Error || type == LogType.Exception)
        {

            //写入log文件
            string str = DateTime.Now.ToString("HH:mm:ss") + "  " + message + "\n" + tag;
            Loger.WriteLogForFile(str);
        }
    }

    private void OnDestroy()
    {
        Application.logMessageReceived -= HandleLog;
    }
}
